// pages/SCM/store/goods/goods.js
const app = getApp()
const util = require('../../../../utils/util.js')
const lbbService = require('../../../service/service.js')
const printUtil = require('../../../../utils/hprt_blue_print_util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    categories: [],
    tabNum: '',
    pageNum: 1,
    pageSize: 15,
    goodsList: [],
    goodsStatIds: [],
    hideFlag: true,
    warehouses: [],
    haveLogisticsList: [{
      id: 0,
      name: '无物流',
      checked: true
    }, {
      id: 1,
      name: '有物流',
      checked: false
    }],
    sendTypes: [{
      id: 1,
      name: '个人仓库',
      checked: true
    }, {
      id: 2,
      name: '现场',
      checked: false
    }],
    sendType: 1,
    haveLogisticsId: 0,
    applyStatus: [{
      id: '',
      name: '寄出物品'
    }, {
      id: 0,
      name: '待收货'
    }, {
      id: 1,
      name: '已收货'
    }],
    uindex: 0,
    imgArray: [],
    sufNum: 1,
    hidePrintCountFlag: true,
    printSleAddr: "收货地址",
    printSelApply: "寄出物品",
    items: [{
        name: "收货地址",
        checked: true,
        value: "收货地址"
      },
      {
        name: "寄出物品",
        checked: true,
        value: "寄出物品"
      }
    ],
    printSelContents: ["收货地址", "寄出物品"],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDefalutAddress();
    this.getUsers();
    this.getMasterInfoByUid();
    this.getCurUserHasRoles();
    this.setData({
      scrollHeight: app.getScrollHeight(0)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    that.toast = that.selectComponent("#toast")
    this.personalModal = this.selectComponent("#personalModal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    //
    //添加物品
    if (this.data.addGoodsFlag) {
      that.setData({
        show: false
      })
      let list = this.data.selGoodsList
      for (var i = 0; i < list.length; i++) {
        this.selGoodsAdd(list[i]);
      }
      this.data.selGoodsList = [];
      that.setData({
        show: true
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  haveLogisticsChange: function (e) {
    this.setData({
      haveLogisticsId: e.detail.value
    })
  },
  sendTypeChange: function (e) {
    this.setData({
      sendType: e.detail.value,
      goodsList: [],
      goodsStatIds: []
    })
  },
  goodsSendItem: function (e) {
    let item = e.target.dataset.item;
    wx.navigateTo({
      url: '../goodsSendItem/goodsSendItem?id=' + item.id,
    })
  },


  getDefalutAddress: function () {
    lbbService.getDefalutAddress({}, function (res) {
      let selectAddress = res.data;
      if (selectAddress) {
        that.setData({
          selectAddress: selectAddress
        });
      }

    });
  },

  getUsers: function () {
    let that = this
    lbbService.getStockUsers({}, function (res) {
      let firstItem = {
        'masterName': '无',
        'masterUid': ''
      };
      res.data.unshift(firstItem);
      let userNames = [];
      res.data.forEach(item => {
        userNames.push(item.masterName)
      })
      that.setData({
        userNames: userNames,
        users: res.data
      })
    })
  },
  userChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)

    if (e.detail.value > 0 && this.data.optaction == '2') {
      this.setData({
        uindex: e.detail.value,
        goodsList: [],
        goodsStatIds: []
      })
    } else {
      this.setData({
        uindex: e.detail.value
      })
    }
    //
  },
  inputLogisticsNum: function (e) {
    let logisticsNum = e.detail.value;
    this.setData({
      logisticsNum: logisticsNum
    })
  },
  //扫码获取物流编号
  scanQrCode: function () {
    let that = this
    wx.scanCode({
      success(res) {
        that.setData({
          logisticsNum: res.result
        });
      }
    })
  },
  toggleTab: function (e) {
    let id = e.currentTarget.dataset.id;
    if (id !== this.data.tabNum) {
      this.setData({
        tabNum: id,
        pageNum: 1
      });
      if (id !== '') {
        this.goodsSendList();
      }

    }

  },
  getMore: function () {
    if (this.data.tabNum === '') {
      return;
    }
    this.data.pageNum += 1;
    this.goodsSendList();
  },
  getFirst: function () {
    if (this.data.tabNum === '') {
      return;
    }
    this.data.pageNum == 1;
    this.goodsSendList();
  },
  goodsSendList: function () {
    let that = this;
    let params = {};
    // if(!that.data.getMore){
    //      that.data.pageNum=1;
    // }
    // that.data.getMore=false;
    let tabNum = that.data.tabNum;
    if (tabNum !== '') {
      params.sendStatus = tabNum
    }
    params.pageNum = that.data.pageNum;
    params.pageSize = that.data.pageSize;
    lbbService.goodsSendList(params, function (res) {
      let goodsSendList = res.data;
      if (goodsSendList && goodsSendList.length > 0) {
        goodsSendList.forEach(e => {
          let details = e.goodsAccessDetails;
          let strs = [];
          details.forEach(item => {
            strs.push(item.goods.name + ' X' + item.goodsNum);
          })
          let str = strs.join('、');
          e.goodsStrs = str;
        })
      }

      if (that.data.pageNum > 1) {
        goodsSendList = that.data.goodsSendList.concat(res.data);
      }
      that.setData({
        goodsSendList: goodsSendList
      });
    });

  },

  getAdminWarehouses: function () {
    let that = this
    lbbService.getAdminWarehouses({}, function (res) {

      if (res.data && res.data.length > 0) {
        that.setData({
          warehouses: res.data,
          warehouseId: res.data[0].id,
          warehouseName: res.data[0].name
        })
      }
    })
  },
  getCurUserHasRoles: function () {
    let that = this;
    lbbService.getCurUserHasRoles({}, function (res) {
      let curUser = {};
      if (res.data) {
        curUser = res.data;
        if (res.data.roleIds) {
          let arr = res.data.roleIds.split(',');
          if (arr && arr.indexOf('3') != -1) { //安装师傅

          } else {
            that.getWarehouseAndThirdParty();
          }
        }
      }
      that.setData({
        curUser: curUser
      });
    });
  },
  getWarehouseAndThirdParty: function () {
    let that = this
    lbbService.getWarehouseAndThirdParty({}, function (res) {
      let warehouseAndThirdPartys = res.data;
      let addwarehouse = {
        id: -1,
        name: '添加类型',
        thirdFlag: '1'
      };
      warehouseAndThirdPartys.push(addwarehouse);
      that.setData({
        warehouseAndThirdPartys: warehouseAndThirdPartys,
        warehouseAndThirdPartyId: warehouseAndThirdPartys[0].id,
        warehouseAndThirdPartyName: warehouseAndThirdPartys[0].name,
        thirdFlag: warehouseAndThirdPartys[0].thirdFlag,
      })
    })
  },
  chooseWarehouseAndThirdParty: function (e) {
    let that = this
    let item = e.currentTarget.dataset.item;
    that.setData({
      warehouseAndThirdPartyId: item.id,
      warehouseAndThirdPartyName: item.name,
      thirdFlag: item.thirdFlag,
      goodsList: [],
      goodsStatIds: []
    });

  },
  thirdNameInp: function (e) {
    let thirdName = e.detail.value;
    this.setData({
      thirdName: thirdName
    })
  },
  showModel: function () {
    this.setData({
      hideFlag: false
    })
  },

  hideModel: function () {
    this.setData({
      hideFlag: true
    })
  },
  selGoodsAdd: function (selectGoods) {
    let index = this.data.goodsList.findIndex(item => item.goodsId == selectGoods.goodsId);
    if (index > -1) {
      this.data.goodsList[index].addNum = selectGoods.addNum;
    } else {
      this.data.goodsList.push(selectGoods);
    }

    this.setData({
      goodsList: this.data.goodsList
    });
    this.data.addGoodsFlag = false;
  },
  toAddWarehouseGoods: function () {
    let params = '?optaction=2';
    let uid = this.data.curUid;
    let uname = this.data.curUname;
    let hideStockNum = true;
    let selGoodsList = [];
    this.data.goodsList.forEach(item => {
      selGoodsList.push({
        goodsId: item.goodsStatId,
        goodsName: item.goodsName,
        addNum: item.addNum
      })
    })
    if (this.data.sendType == 1 && !this.data.warehouseAndThirdPartyId) { //个人仓库
      params += '&uid=' + uid + '&uname=' + uname + '&selGoodsList=' + JSON.stringify(selGoodsList);
      hideStockNum = false;
    }
    if (this.data.warehouseAndThirdPartyId > -1 && !this.data.thirdFlag) { //仓库发货
      params = '?optaction=1';
      params += '&warehouseId=' + this.data.warehouseAndThirdPartyId + '&warehouseName=' + this.data.warehouseAndThirdPartyName + '&selGoodsList=' + JSON.stringify(selGoodsList);
      hideStockNum = false;
    }
    this.setData({
      hideStockNum: hideStockNum
    });
    wx.navigateTo({
      url: '../chooseGoods/chooseGoods' + params,
    })
  },
  copyGoodsInfo: function (e) {
    let item = e.target.dataset.item;
    wx.setClipboardData({
      data: item.goodsStrs,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })

  },
  copyReceive: function (e) {
    let item = e.target.dataset.item;
    let str = '';
    str += '寄件人：' + item.fromUserName + '\n';
    str += '收货人：' + item.toUserName + '\n';
    if (item.receivePerson)
      str += '收货人名称：' + item.receivePerson + '\n';
    if (item.receivePhone)
      str += '收货人联系方式：' + item.receivePhone + '\n';
    if (item.receiveAddress)
      str += '收货人联系方式：' + item.receiveAddress + '\n';
    str += '寄出物品：' + item.goodsStrs + '\n';
    wx.setClipboardData({
      data: str,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  inputName: function (e) {
    console.log('e====', e)
    let inputName = e.detail.value;
    let addNum = parseInt(inputName);
    let item = this.data.goodsList[e.currentTarget.dataset.index];
    if (addNum > item.goodsNum) {
      wx.showToast({
        title: '请小于库存数量',
        image: '/images/gantan.png'
      })
      item.addNum = '';
    } else {
      item.addNum = addNum;
    }
    this.setData({
      goodsList: this.data.goodsList
    });

  },
  deleteGoods: function (e) {
    let index = e.currentTarget.dataset.index;
    this.data.goodsList.splice(index, 1);
    this.data.goodsStatIds.splice(index, 1);
    this.setData({
      goodsList: this.data.goodsList
    });
  },
  toChooseAddress: function () {
    wx.navigateTo({
      url: '../chooseAddress/chooseAddress',
    })
  },
  getMasterInfoByUid: function () {
    let that = this;
    lbbService.getMasterInfoByUid({}, function (res) {
      that.setData({
        curUid: res.data.masterUid,
        curUname: res.data.masterName
      });

    })
  },
  //表单提交前确认
  formSubmit: function (e) {
    let that = this
    let formData = e.detail.value
    console.log(e)
    if (that.data.uindex == 0) {
      wx.showToast({
        title: '请选择收货人',
        image: '/images/gantan.png'
      })
      return;
    }
    if (that.data.haveLogisticsId == 1) {
      if (!formData.receivePerson || !formData.receivePhone || !formData.receiveAddress) {
        that.toast.showToast('请输入收货人名称电话地址信息');
        return;
      }

    }
    formData.toUid = that.data.users[that.data.uindex].masterUid;
    if (that.data.warehouseAndThirdPartyId == -1 && !that.data.thirdName) {
      wx.showToast({
        title: '请输入寄出类型',
        image: '/images/gantan.png'
      })
      return;
    }
    if (that.data.thirdFlag) {
      formData.sendType = 3; //选择添加类型时候，传3
    }

    let goodsList = this.data.goodsList;
    if (goodsList.length == 0) {
      wx.showToast({
        title: '请添加物品',
        image: '/images/gantan.png'
      })
      return;
    }
    let flag = true;
    let goodsDetails = [];
    goodsList.forEach(item => {
      try {
        if (!item.addNum) {
          flag = false;
          that.toast.showToast(item.goodsName + '数量需大于零');
          throw new Error();
          return false;
        }
        let goodsDetail = {};
        goodsDetail.goodsId = item.goodsStatId;
        goodsDetail.goodsNum = item.addNum;
        goodsDetails.push(goodsDetail);
      } catch (e) { };

    });
    if (!flag) {
      return;
    }
    formData.detailJsonStr = JSON.stringify(goodsDetails);
    that.setData({
      formData: formData
    });
    let modalText = '确定寄出物品吗？'
    that.personalModal.showModal(modalText, that.uploadImg);

  },
  uploadImg:function(){
    let that = this
    let imgArray = that.data.imgArray
    wx.showLoading({
      title: '正在上传图片',
    })
    util.upLoadImg(app.globalData.header, imgArray, 0, [], that.goodsSendSubmit)
  },

  goodsSendSubmit: function (imgIdArray) {
    let that = this
    wx.hideLoading()
    let formData = that.data.formData;
    let imgIds = imgIdArray.join();
    if (imgIds) {
      formData.imgIds = imgIds;
    }
    lbbService.goodsSend(formData, function (res) {
      wx.showToast({
        title: '提交成功',
      })
      that.setData({
        tabNum: 0,
        pageNum: 1,
        imgIdArray: []
      });
      setTimeout(function () {
        // wx.navigateBack({
        //   delta: 1
        // })
        that.goodsSendList();
      }, 1500)
    })

  },

  addImg: function (e) {
    let that = this;
    wx.chooseImage({
      count: 6,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          that.data.imgArray.push(res.tempFilePaths[i])
        }
        that.setData({
          imgArray: that.data.imgArray
        })
        console.log(that.data.imgArray)
      }
    })
  },
  deleteImg: function (e) {
    let that = this
    let deleteIndex = e.currentTarget.dataset.index
    that.data.imgArray.splice(deleteIndex, 1)
    that.setData({
      imgArray: that.data.imgArray
    })
  },

  hprtPrint:function(e){

    let item = e.target.dataset.item;
    this.data.allPrintData = item;
    this.getPrintContent(item);
    this.setData({
      hidePrintCountFlag: false
    })

  },
  getPrintContent: function (item) {
    let str = '';
    let lineHeight = 40;
    let y = 110;//留出打印时间及份数的数据

    let selContents = this.data.printSelContents;
    if (selContents.indexOf(this.data.printSleAddr) != -1) {
      let lineHeight = 25,
        startX = 10,
        firstLineLen = 30,
        secondLineLen = 25,
        xM = 1,
        yM = 1;

      if (this.data.printSelContents.length == 1) {
        xM = 3;
        yM = 3;
        firstLineLen = 11;
        secondLineLen = 10;
        lineHeight = 60;
      }

      let sendUserStr = '寄件人：' + item.fromUserName;
      let rstTxt = printUtil.txtHandle(sendUserStr, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM);
      str += rstTxt.str;
      y = rstTxt.y;

      let applyUserStr = '收货人:' + item.toUserName;
      rstTxt = printUtil.txtHandle(applyUserStr, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM);
      str += rstTxt.str;
      y = rstTxt.y;

      if (item.receivePerson) {
        let receivePerson = '收货人名称:' + item.receivePerson;
        let rstTxt = printUtil.txtHandle(receivePerson, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM);
        str += rstTxt.str;
        y = rstTxt.y;
      }
      if (item.receivePhone) {
        let receivePhone = '收货人手机:' + item.receivePhone;
        let startX = 10;
        let firstLineLen = 20;
        let rstTxt = printUtil.txtHandle(receivePhone, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM);
        str += rstTxt.str;
        y = rstTxt.y;
      }
      if (item.receiveAddress) {
        let txt = '收货地址:' + item.receiveAddress;
        let rstTxt = printUtil.txtHandle(txt, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM);
        str += rstTxt.str;
        y = rstTxt.y;
      }
    }

    if (selContents.indexOf(this.data.printSelApply) != -1) {
      let goodsArr = item.goodsStrs.split("、");
      let txt = '寄出物品:';
      let rstTxt = printUtil.txtHandle(txt, lineHeight, y);
      str += rstTxt.str;
      y = rstTxt.y;
      let xM = 2;
      let yM = 2;
      let font = "0";
      let goodsLineHeight = 60;
      let firstLineLen = 11;
      let secondLineLen = 10;
      let startX = 35;
      for (var i = 0; i < goodsArr.length; i++) {
        let goodsTxt = (i + 1) + "." + goodsArr[i];
        let rstTxt = printUtil.txtHandle(goodsTxt, goodsLineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
        str += rstTxt.str;
        y = rstTxt.y;
      }
    }

    if (str == '') {
      wx.showModal({
        title: '提示',
        content: '没有选择要打印的内容',
      })
    }

    this.data.printContent = str;
  },
  sufNumInp: function (e) {
    let sufNum = e.detail.value;
    this.setData({
      sufNum: sufNum
    })
  },
  hideModal: function () {
    this.setData({
      hideFlag: true,
      hidePrintCountFlag: true
    });
  },
  stopMaoPao: function () {
    return true;
  },
  checkSubmit: function (e) {
    let that = this;
    if (that.data.sufNum !== '0') {
      var r = /^\+?[1-9][0-9]*$/;
      if (!r.test(that.data.sufNum)) {
        that.toast.showToast('请输入大于0的整数');
        return false;
      }
    }

    printUtil.print(that.data.printContent, that.data.sufNum);
    that.setData({
      hidePrintCountFlag: true,
      sufNum: 1
    })

  },
  checkboxPrintSelChange: function (e) {
    console.log("打印内容选择打印", e);
    this.data.printSelContents = e.detail.value;
    if (!this.data.printSelContents || this.data.printSelContents.length == 0) {
      wx.showModal({
        title: '提示',
        content: '请选择至少一个要打印的内容',
      })
    } else {
      this.getPrintContent(this.data.allPrintData);
    }
  }

})
